package top.csy8888.ch11.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author CSY
 * @date 2025 - 09 - 27
 */
@Configuration
public class RedisConfig {

    /**
     * 自定义RedisTemplate，主要是自定义键值的序列化类型
     * @param factory 注入的连接工厂
     * @return
     */
    @Bean
    public RedisTemplate<String, ?> redisTemplate(RedisConnectionFactory factory) {
        //创建RedisTemplate实例
        RedisTemplate<String,?> template = new RedisTemplate<>();
        //设置连接工厂，不设置无法初始化
        template.setConnectionFactory(factory);
        //自定义key的序列化器(使用StringRedisSerializer)
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        template.setKeySerializer(keySerializer);
        template.setHashKeySerializer(keySerializer);

        //自定义value的序列化器
        GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
        template.setValueSerializer(valueSerializer);
        template.setHashValueSerializer(valueSerializer);
        return template;
    }
}
